package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.DishFlavor;
import com.itheima.common.pageParm;
import com.itheima.dao.DishDao;
import com.itheima.dto.DishDto;
import com.itheima.exception.CustomException;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.dishService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Transactional
public class dishServiceImpl implements dishService {


    @Resource
    private DishDao dishDao;

    @Lazy
    @Resource
    private CategoryService categoryService;

    @Resource
    private DishFlavorService dishFlavorService;

    /*
     * 根据分类查询，查询出来该分类的所有菜品
     * */
    @Override
    public List<DishDto> findByCategoryId(long categoryId, Integer status) {

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();

        lqw.eq(Dish::getCategoryId, categoryId);

        //追加状态值条件
        lqw.eq(status != null, Dish::getStatus, status);


        List<Dish> dishList = dishDao.selectList(lqw);

        //要包装每个菜品的口味数据！
        List<DishDto> dishDtoList = dishList.stream().map(dish -> {

            DishDto dto = new DishDto();

            List<DishFlavor> dishFlavorList = dishFlavorService.findByDishId(dish.getId());

            //把每个菜品的口味数据集合封装到dto里面
            dto.setFlavors(dishFlavorList);

            //将菜品数据封装到dto里面
            BeanUtils.copyProperties(dish, dto);

            return dto;

        }).collect(Collectors.toList());


        return dishDtoList;
    }

    @Override
    public int add(DishDto dishDto) {

        //往菜品表添加数据
        int row = dishDao.insert(dishDto);

        //只有当菜品表添加成功了，并且这个菜品是有口味数据的，才执行if操作
        if (row > 0 && dishDto.getFlavors() != null && dishDto.getFlavors().size() > 0) {
            int row2 = 0;
            for (DishFlavor flavor : dishDto.getFlavors()) {


                //设置口味数据哪一种菜
                flavor.setDishId(dishDto.getId());

                //把每一个口味数据添加到口味表
                row2 += dishFlavorService.add(flavor);
            }
            return row2 == dishDto.getFlavors().size() ? 1 : 0;
        }
        return row;
    }

    @Override
    public IPage<DishDto> findPage(pageParm pageParm) {

        IPage<Dish> p = new Page<>(pageParm.getPage(), pageParm.getPageSize());

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();

        lqw.like(pageParm.getName() != null, Dish::getName, pageParm.getName());

        IPage<Dish> dishIPage = dishDao.selectPage(p, lqw);

        List<DishDto> dtoList = dishIPage.getRecords().stream().map((dish) -> {


            //查询分类
            Category category = categoryService.findById(dish.getCategoryId());

            //查询口味
            List<DishFlavor> flavorList = dishFlavorService.findByDishId(dish.getId());

            DishDto dishDto = new DishDto();

            dishDto.setCategoryName(category.getName());
            dishDto.setFlavors(flavorList);

            BeanUtils.copyProperties(dish, dishDto);

            return dishDto;

        }).collect(Collectors.toList());


        IPage<DishDto> dishDtoIPage = new Page<>();

        dishDtoIPage.setRecords(dtoList);

        dishDtoIPage.setTotal(dishIPage.getTotal());

        return dishDtoIPage;


    }

    @Override
    public int update(DishDto dishDto) {

        //先更新菜品表 按照id来更新
        int row = dishDao.updateById(dishDto);

        //2.再更新口味表
        if (row > 0) {
            //2.1先把这个菜品的口味数据删除掉
            int row2 = dishFlavorService.deleteByDishId(dishDto.getId());
            //2.2再把这个菜品的口味数据添加进来
            List<DishFlavor> flavorList = dishDto.getFlavors();

            //2.2.1 先判断页面有没有给过来口味数据，如果有就添加，没有就不添加
            if (flavorList != null && flavorList.size() > 0) {


                int row3 = 0;
                //遍历每一个口味数据
                for (DishFlavor dishFlavor : flavorList) {

                    dishFlavor.setDishId(dishDto.getId());

                    row3 += dishFlavorService.add(dishFlavor);
                }
                return row3 == flavorList.size() ? 1 : 0;
            }
        }

        return row;


    }

    @Override
    public int delete(List<Long> ids) {



        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();

        lqw.in(Dish::getId, ids);

        lqw.eq(Dish::getStatus,1);//1是起售

        int total=dishDao.selectCount(lqw);

        if (total > 0) {
            throw new CustomException("有菜品处于启售状态，禁止删除！");
        }

        int row=dishDao.deleteBatchIds(ids);
        //先把这些要删除的菜品口味数据删掉，然后再删除这些菜品
        for (Long id : ids) {
            dishFlavorService.deleteByDishId(id);

        }
        return row==ids.size()? 1:0;
    }

    @Override
    public int updateStatusByIds(List<Long> ids, int status) {
        int row = 0;
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            row += dishDao.updateById(dish);
        }
        return row;
    }

    @Override
    public Dish findByDishId(Long dishId) {

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();

        lqw.eq(Dish::getId,dishId);
       return dishDao.selectOne(lqw);
    }
}
